<?php

namespace App\Services;

class TreeConverter
{
    public function convertToThreeLevelTree(array $data): array
    {
        $tree = [];

        foreach ($data as $item) {
            if (!isset($item['namePath']) || !isset($item['value'])) {
                continue;
            }

            $pathParts = explode('/', $item['namePath']);
            
            if (count($pathParts) !== 3) {
                continue;
            }

            list($level1, $level2, $level3) = $pathParts;

            // 构建三级树结构
            if (!isset($tree[$level1])) {
                $tree[$level1] = [];
            }
            
            if (!isset($tree[$level1][$level2])) {
                $tree[$level1][$level2] = [];
            }
            
            $tree[$level1][$level2][$level3] = $item['value'];
        }

        return $tree;
    }

    public function formatTreeForOutput(array $tree): string
    {
        return json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
     // 新增方法：返回JSON格式的树结构
    public function formatTreeAsJson(array $tree): string
    {
        return json_encode($tree, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }
}
